#include "mainui.h"
#include "ui_mainui.h"
#include <QDebug>
#include <QMenu>
#include <QJsonDocument>
#include <QFile>
#include <QMessageBox>
#include <QThread>
#include <QNetworkAccessManager>
#include <QJsonObject>
#include <QNetworkReply>
#include <QJsonArray>
#include <QJsonValueRef>
#include "mytreewidgetitem.h"
#include "mytcpsocket.h"


MainUI::MainUI(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainUI)
{
    ui->setupUi(this);

    // 窗口渲染
    setQssStyle(QString("../style/MainStyle.qss"),this);
    // 设置窗口背景透明
    this->setAttribute(Qt::WA_TranslucentBackground);
    // 设置无边框窗口
    this->setWindowFlags(Qt::FramelessWindowHint);
    // 关闭销毁窗口
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 隐藏滚动条
    ui->treeWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //垂直滚动条
    ui->treeWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //水平滚动条
    // 设置窗口透明度
    // this->setWindowOpacity(0.95);
    sunsetNum = 0;

    // 初始化信号槽
    initSigSlot();

    // 初始化设置列表
    initSetList();

    ui->lab_head->installEventFilter(this);
    ui->lab_tqyb->installEventFilter(this);


}

MainUI::~MainUI()
{
    delete ui;
}

void MainUI::loadFriendsGroups()
{
    //初始化TreeWidget
    initTreeWidget();
    //加载好友列表
    for(int i = 0;i<GlobalObject::getGlobalObject()->getUserInfo().friend_list.size();i++){
        st_friendData fdata = GlobalObject::getGlobalObject()->getUserInfo().friend_list[i];
        QTreeWidgetItem* child = new QTreeWidgetItem(root_friend);   //创建新节点
        root_friend->addChild(child);   //添加到根节点下
        struct st_treeItem data(fdata,TI_FRIEND);
        MyTreeWidgetItem* item = new MyTreeWidgetItem(data,this);
        //关键,存储每个用户的UID 定义角色数据(隐藏数据), 获取数据时要用相对应的角色
        child->setData(0,Qt::UserRole,QVariant(data.fdata.dd_num));
        ui->treeWidget->setItemWidget(child,0,item);

        map_treeitem.insert(fdata.dd_num,item);
    }

    // 加载群列表
    for(int i = 0;i<GlobalObject::getGlobalObject()->getUserInfo().group_list.size();i++){
        st_gData gdata = GlobalObject::getGlobalObject()->getUserInfo().group_list[i];
        QTreeWidgetItem* child = new QTreeWidgetItem(root_group);   //创建新节点
        root_group->addChild(child);
        struct st_treeItem data(gdata,TI_GROUP);
        MyTreeWidgetItem* item = new MyTreeWidgetItem(data,this);
        //关键,存储每个群的ID 定义角色数据(隐藏数据), 获取数据时要用相对应的角色
        child->setData(0,Qt::UserRole,QVariant(data.gdata.gid));
        ui->treeWidget->setItemWidget(child,0,item);
        map_treeitem.insert(gdata.gid,item);
    }

}



void MainUI::initTreeWidget()
{
    //设置缩进,所有子节点和根节点对齐(0是完全对齐,但没有展开箭头)
    ui->treeWidget->setIndentation(0);
    //设置item的图标大小
    ui->treeWidget->setIconSize(QSize(40,40));

    root_friend = new QTreeWidgetItem(ui->treeWidget);
    root_friend->setText(0,"我的好友");
    ui->treeWidget->addTopLevelItem(root_friend);  //添加好友根节点

    root_group = new QTreeWidgetItem(ui->treeWidget);
    root_group->setText(0,"群聊");
    ui->treeWidget->addTopLevelItem(root_group);  //添加群聊根节点

    //节点默认展开
    ui->treeWidget->expandAll();

    menu = new QMenu(ui->treeWidget);

    // 搜索栏
    QAction* action_seek = new QAction(ui->le_seek);
    action_seek->setIcon(QIcon(":/prefix2/software/seek.png"));
    ui->le_seek->addAction(action_seek,QLineEdit::LeadingPosition);
}


void MainUI::initNoticeWindow()
{
    noticewindow = new NoticeWindow;

    //更新通知图标
    connect(noticewindow,SIGNAL(noticeIconStatus(int)),this,SLOT(updateNoticeIcon(int)));
}

void MainUI::initSigSlot()
{
    // 登录成功,接收传递的用户信息结构体,初始化主界面
    connect(this,SIGNAL(login_success()),this,SLOT(slot_login_success()));
    // 好友登录通知,更新好友列表UI
    connect(this,SIGNAL(sign_friendStatus_change(int,int)),this,SLOT(updateFriendStatus(int,int)));
    // 删除我的好友节点下的Item
    connect(this,SIGNAL(sign_deleteFriend(int)),this,SLOT(removeFriendItem(int)));
    // 添加我的好友节点下的Item
    connect(this,SIGNAL(sign_addFriend(QVariant)),this,SLOT(addFriendItem(QVariant)));
    // 添加群聊节点Item
    connect(this,SIGNAL(sign_addGroup(int)),this,SLOT(addGroupItem(int)));
    // 删除群聊节点Item
    connect(this,SIGNAL(sign_deleteGroup(int)),this,SLOT(removeGroupItem(int)));
    // 处理私聊消息文本
    connect(this,SIGNAL(sign_privateChatMsg(QVariant)),this,SLOT(slot_privateChatMsg(QVariant)));
    // 处理群聊消息文本
    connect(this,SIGNAL(sign_groupChatMsg(QVariant)),this,SLOT(slot_groupChatMsg(QVariant)));

    //初始化(我的好友)右键菜单项
    action_userinfo = new QAction("查看资料",this);
    private_chat = new QAction("发送即时消息",this);
    delete_friend = new QAction("删除好友",this);

    //删除好友的信号槽
    connect(delete_friend,&QAction::triggered,this,[=](){
        QMessageBox msgbox(QMessageBox::Information,"DragonIM","确定要删除好友吗?",QMessageBox::Yes|QMessageBox::Cancel);
        int ret = msgbox.exec();
        if(ret == QMessageBox::Yes){
            //发送删除好友报文
            QVariantMap map;
            map["cmd"]="delete_friend";
            map["user"]=GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num;
            map["friend"]=GlobalObject::getGlobalObject()->getCurrentSelectUid();

            //发送请求
            GlobalObject::getGlobalObject()->sendRequest(map);
        }

    });

    //查看用户信息信号槽
    connect(action_userinfo,&QAction::triggered,this,[=](){
        struct st_friendData fdata = GlobalObject::getGlobalObject()->getFriendInfo(GlobalObject::getGlobalObject()->getCurrentSelectUid());
        map_finfowindow[fdata.dd_num]->show();
    });

    //发起聊天的信号槽
    connect(private_chat,&QAction::triggered,this,[=](){
        struct st_friendData fdata = GlobalObject::getGlobalObject()->getFriendInfo(GlobalObject::getGlobalObject()->getCurrentSelectUid());
        // 打开窗口表示未读消息已全部读完
        emit map_treeitem[fdata.dd_num]->sig_noread_flag(1);
        map_chatwindow[fdata.dd_num]->show();

        // 创建动画
//        QPropertyAnimation *animation = new QPropertyAnimation(map_chatwindow[fdata.dd_num], "geometry");
//        animation->setDuration(1000); // 设置动画持续时间，例如1秒
//        animation->setStartValue(geometry()); // 设置开始值为当前几何形状
//        animation->setEndValue(QRect(0, 0, 800, 600)); // 设置结束值为放大的几何形状
//        animation->setEasingCurve(QEasingCurve::InOutQuad); // 设置缓动曲线，使动画更自然
//        animation->start(QPropertyAnimation::DeleteWhenStopped); // 启动动画，并在结束时删除动画对象
    });

    // 初始化(群聊)右键菜单项
    action_groupinfo = new QAction("查看群资料",this);
    group_chat = new QAction("发送群消息",this);
    quit_group = new QAction("退出群聊",this);

    //查看群资料信号槽
    connect(action_groupinfo,&QAction::triggered,this,[=](){
        struct st_gData gdata = GlobalObject::getGlobalObject()->getGroupInfo(GlobalObject::getGlobalObject()->getCurrentSelectGid());
        map_ginfowindow[gdata.gid]->Show();
    });

    //发送群消息的信号槽
    connect(group_chat,&QAction::triggered,this,[=](){
        struct st_gData gdata = GlobalObject::getGlobalObject()->getGroupInfo(GlobalObject::getGlobalObject()->getCurrentSelectGid());
        // 打开窗口表示未读消息已全部读完
        emit map_treeitem[gdata.gid]->sig_noread_flag(3);
        map_groupchatwindow[gdata.gid]->Show();
    });

    //退出群聊信号槽
    connect(quit_group,&QAction::triggered,this,[=](){
        //选中的群聊ID
        int gid = GlobalObject::getGlobalObject()->getCurrentSelectGid();
        struct st_gData gdata = GlobalObject::getGlobalObject()->getGroupInfo(gid);
        // 用户ID
        int uid = GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num;
        QVariantMap map;
         // 群主解散群聊
        if(gdata.gboss == uid){
            QMessageBox msgbox(QMessageBox::Information,"DragonIM","您是群主,退出群聊将会解散该群,\n确定要退出吗?",QMessageBox::Yes|QMessageBox::Cancel);
            int ret = msgbox.exec();
            if(ret == QMessageBox::Yes){
                //发送解散群聊请求
                QString quit_group;
                map["cmd"]="dissolve_group";
                map["gid"]=gid;
                map["uid"]=uid;
            }
        }
        // 群员退出群聊
        else{
            QMessageBox msgbox(QMessageBox::Information,"DragonIM","确定要退出群聊吗?",QMessageBox::Yes|QMessageBox::Cancel);
            int ret = msgbox.exec();
            if(ret == QMessageBox::Yes){
                //从群聊列表删除群聊
                GlobalObject::getGlobalObject()->deleteGroupFromList(gid);
                //从TreeWidget中删除群聊(更新界面)
                removeGroupItem(gid);
                //发送退出群聊请求
                QString quit_group;
                map["cmd"]="quit_group";
                map["gid"]=gid;
                map["uid"]=uid;
            }
        }
        //发送请求
        GlobalObject::getGlobalObject()->sendRequest(map);
    });

}

void MainUI::initSetList()
{
    set_menu = new QMenu(this);
    aboutDIM = new QAction("关于龙通讯",this);
    modify_pwd = new QAction("修改密码",this);
    modify_info = new QAction("编辑个人资料",this);
    chat_AI = new QAction("AI聊天",this);                   // AI聊天
    open_hy = new QAction("开通会员",this);                  // 开通会员

    // 将QAction添加到菜单
    set_menu->addAction(chat_AI);
    set_menu->addAction(open_hy);
    set_menu->addAction(modify_info);
    set_menu->addAction(modify_pwd);
    set_menu->addAction(aboutDIM);

    // 将菜单添加到按钮
    // ui->btn_set->setMenu(set_menu);
    // set_menu->setCursor(Qt::PointingHandCursor);  // 此属性保存光标小手形状

    // AI聊天
    connect(chat_AI,&QAction::triggered,this,[=](){
        aichatwindow->show();
    });

    // 开通会员
    connect(open_hy,&QAction::triggered,this,[=](){
        QMessageBox::information(this,"消息","已成功开通会员!");
    });

    // 编辑个人资料
    connect(modify_info,&QAction::triggered,this,[=](){
        modifyinfowindow->show();
    });

    // 修改密码
    connect(modify_pwd,&QAction::triggered,this,[=](){
        modifypwdwindow->Show();
    });

    // 关于龙通讯
    connect(aboutDIM,&QAction::triggered,this,[=](){
        aboutDIMwindow->show();
    });
}

void MainUI::getWeather()
{
    QUrl url("https://api.openweathermap.org/data/2.5/weather?lat=26.50&lon=114.14&appid=101fb88cd8785cdac4fdaf359c0e71b3");
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QNetworkRequest request(url);
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply) {
        if (reply->error() != QNetworkReply::NoError) {
            qDebug()<<reply->errorString();
        } else {
//            QByteArray response = reply->readAll();
//            QJsonDocument json = QJsonDocument::fromJson(response);
//            QJsonObject obj = json.object();
//                    QString formatted;
//            formatted.append("<b>");
//            formatted.append(obj.value("name").toString());
//            formatted.append("</b><br>");
//                    QJsonObject main = obj.value("main").toObject();
//            formatted.append(QString("Temperature: %1°C <br> Humidity: %2% <br> Pressure: %3 hPa <br>").arg(main.value("temp").toDouble()).arg(main.value("humidity").toDouble()).arg(main.value("pressure").toDouble()));
//                    QJsonObject wind = obj.value("wind").toObject();
//            formatted.append(QString("Wind Speed: %1 m/s <br> Direction: %2° <br>").arg(wind.value("speed").toDouble()).arg(wind.value("deg").toDouble()));
//                    QJsonArray weather = obj.value("weather").toArray();
//            formatted.append("<hr><img src=http://openweathermap.org/img/w/");
//            formatted.append(weather.at(0).toObject().value("icon").toString());
//            formatted.append(".png> ");
//            formatted.append(weather.at(0).toObject().value("description").toString());
//            formatted.append("<br>");
//            qDebug()<<formatted;


            QString answer = reply->readAll();

            QJsonDocument jsonResponse = QJsonDocument::fromJson(answer.toUtf8());

            QJsonObject jsonObject = jsonResponse.object();

            qDebug() << "Weather in" << jsonObject["name"].toString();
            qDebug() << "Degrees" << jsonObject["main"].toObject()["temp"].toDouble() - 273.15; // Convert to C
            qDebug() << "Description" << jsonObject["weather"][0]["description"].toString();
            qDebug() << "Humidity" << jsonObject["main"].toObject()["humidity"].toInt();
            qDebug() << "Wind speed" << jsonObject["wind"].toObject()["speed"].toDouble();


        }
        reply->deleteLater();
    });
    manager->get(request);

}


void MainUI::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 记录鼠标按下的位置
        dragPosition = event->pos();
        isDragging = true;
    }
}

void MainUI::mouseMoveEvent(QMouseEvent *event)
{
    if (isDragging && (event->buttons() & Qt::LeftButton)) {
        // 计算窗口的新位置
        int dx = event->x() - dragPosition.x();
        int dy = event->y() - dragPosition.y();
        move(x() + dx, y() + dy);
    }
}

void MainUI::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isDragging = false;
    }
}

void MainUI::removeFriendItem(int fuid)
{
     //遍历QTreeWidgetItem
    QTreeWidgetItemIterator it(root_friend);   //遍历好友节点
    while(*it){
        if((*it)->data(0,Qt::UserRole).toInt() == fuid){
            root_friend->removeChild(*it);
            break;
        }
        it++;
    }

    // 从Map中删除对应的好友聊天窗口和好友资料窗口以及treeitem节点
    PrivateChatWindow* p = map_chatwindow[fuid];
    map_chatwindow.remove(fuid);
    delete p;
    FriendInfoWindow* f = map_finfowindow[fuid];
    map_finfowindow.remove(fuid);
    delete f;
    MyTreeWidgetItem* t = map_treeitem[fuid];
    map_treeitem.remove(fuid);
    delete t;
}

void MainUI::addFriendItem(QVariant var)
{
    struct st_friendData fdata = var.value<st_friendData>();
    QTreeWidgetItem* child = new QTreeWidgetItem(root_friend);   //创建新节点
    root_friend->addChild(child);   //添加到根节点下
    struct st_treeItem data(fdata,TI_FRIEND);
    MyTreeWidgetItem* item = new MyTreeWidgetItem(data,this);
    //关键,存储每个用户的UID 定义角色数据(隐藏数据), 获取数据时要用相对应的角色
    child->setData(0,Qt::UserRole,QVariant(data.fdata.dd_num));
    ui->treeWidget->setItemWidget(child,0,item);

    // 添加到Map中
    st_personData udata = GlobalObject::getGlobalObject()->getUserInfo().sdata;
    PrivateChatWindow* pcw = new PrivateChatWindow(udata,fdata);
    FriendInfoWindow* fiw = new FriendInfoWindow(fdata);
    map_chatwindow.insert(fdata.dd_num,pcw);
    map_finfowindow.insert(fdata.dd_num,fiw);
    map_treeitem.insert(fdata.dd_num,item);

    connect(map_finfowindow[fdata.dd_num],&FriendInfoWindow::sig_infoWindowShow,this,[=](int fid){
        map_chatwindow[fid]->show();
    });
}

void MainUI::removeGroupItem(int gid)
{
    //遍历QTreeWidgetItem
   QTreeWidgetItemIterator it(root_group);   //遍历群聊节点
   while(*it){
       if((*it)->data(0,Qt::UserRole).toInt() == gid){
           root_group->removeChild(*it);
           break;
       }
       it++;
   }
   // 从Map中删除对应的群聊天窗口和群资料窗口
   GroupChatWindow* g = map_groupchatwindow[gid];
   map_groupchatwindow.remove(gid);
   delete g;
   GroupInfoWindow* f = map_ginfowindow[gid];
   map_ginfowindow.remove(gid);
   delete f;
   MyTreeWidgetItem* t = map_treeitem[gid];
   map_treeitem.remove(gid);
   delete t;
}

void MainUI::addGroupItem(int gid)
{
    st_gData gdata = GlobalObject::getGlobalObject()->getGroupInfo(gid);
    QTreeWidgetItem* child = new QTreeWidgetItem(root_group);   //创建新节点
    root_group->addChild(child);   //添加到根节点下
    struct st_treeItem data(gdata,TI_GROUP);
    MyTreeWidgetItem* item = new MyTreeWidgetItem(data,this);
    //关键,存储每个用户的UID 定义角色数据(隐藏数据), 获取数据时要用相对应的角色
    child->setData(0,Qt::UserRole,QVariant(data.gdata.gid));
    ui->treeWidget->setItemWidget(child,0,item);

    // 添加到Map中
    st_personData udata = GlobalObject::getGlobalObject()->getUserInfo().sdata;
    GroupChatWindow* gcw = new GroupChatWindow(udata,gdata);
    GroupInfoWindow* gfw = new GroupInfoWindow(gdata);
    map_groupchatwindow.insert(gid,gcw);
    map_ginfowindow.insert(gid,gfw);
    map_treeitem.insert(gid,item);

    connect(gfw,&GroupInfoWindow::sig_ginfoWindowShow,this,[=](int gid){
        map_groupchatwindow[gid]->Show();
    });

}

void MainUI::slot_privateChatMsg(QVariant var)
{
    struct st_msg msg = var.value<struct st_msg>();
    //私聊文本
    if(msg.type == 51){
        // 如果发送方是自己,就更新到接收方的聊天窗口
        if(msg.send == GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num){
            map_chatwindow[msg.recv]->addTextRecord(msg);
        }
        // 否则更新到发送方的聊天窗口
        else{
            map_chatwindow[msg.send]->addTextRecord(msg);
            // 告诉接收方有未读消息(自己发的就不需要显示未读,只有接收到其他人的消息,才显示未读)
            emit map_treeitem[msg.send]->sig_noread_flag(0);
        }

    }
    // 私聊文件
    else if(msg.type == 52){
        if(msg.send == GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num)
             map_chatwindow[msg.recv]->addFileRecord(msg);
        else{
            map_chatwindow[msg.send]->addFileRecord(msg);
            // 告诉接收方有未读消息
            emit map_treeitem[msg.send]->sig_noread_flag(0);
        }
    }
    //私聊表情
    else if(msg.type == 53){
        if(msg.send == GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num)
             map_chatwindow[msg.recv]->addJoyRecord(msg);
        else{
            map_chatwindow[msg.send]->addJoyRecord(msg);
            // 告诉接收方有未读消息(自己发的就不需要显示未读,只有接收到其他人的消息,才显示未读)
            emit map_treeitem[msg.send]->sig_noread_flag(0);
        }
    }


}

void MainUI::slot_groupChatMsg(QVariant var)
{
    struct st_msg msg = var.value<struct st_msg>();
    // 清洗content属性,将其中的群ID和内容分离  content:100000-你好
    int len = msg.contect.length();
    int pos = msg.contect.indexOf('-');             // 第一次出现-的位置
    int gid = msg.contect.left(pos).toInt();        // left()返回前n个字符
    QString data = msg.contect.right(len-pos-1);    // right()返回后n个字符
    // content重新赋值,只包含内容本身
    msg.contect = data;
    // 群聊文字
    if(msg.type == 54){
        // 更新到对应的群聊窗口
        map_groupchatwindow[gid]->addTextRecord(msg);
    }
    // 群聊表情
    else if(msg.type == 55){
        // 更新到对应的群聊窗口
        map_groupchatwindow[gid]->addJoyRecord(msg);
    }

    // 告诉接收方有未读消息
    emit map_treeitem[gid]->sig_noread_flag(2);

}

void MainUI::closeEvent(QCloseEvent *event)
{
    // Q_UNUSED(event);
    // 如果不想关闭窗口,可以调用event->ignore()

    // 给用户良好的体验,确保界面已关闭
    this->hide();

    // 主窗口关闭意味着客户端退出 给服务器发送 用户退出的报文
    int uid = GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num;
    QString user_quit;
    QVariantMap map;
    map["cmd"]="quit";
    map["user"]=uid;

    //发送请求
    GlobalObject::getGlobalObject()->sendRequest(map);

    // 延迟1000ms关闭,直接关闭服务器接收不到quit报文
    QThread::msleep(1000);

}

void MainUI::paintEvent(QPaintEvent *ev)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

bool MainUI::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui->lab_head && event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            // 在这里处理左键点击事件
            modifyinfowindow->show();
            // 可以根据需要执行其他操作，比如发出信号等
            return true; // 返回true表示事件已被处理，不再传递给其他对象
        }
    }
    else if(obj == ui->lab_tqyb && event->type() == QEvent::MouseButtonPress){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            // 在这里处理左键点击事件
            qDebug()<<"天气预报";
            getWeather();
            // 可以根据需要执行其他操作，比如发出信号等
            return true; // 返回true表示事件已被处理，不再传递给其他对象
        }
    }
    // 对于其他事件或对象，继续标准事件处理
    return QObject::eventFilter(obj, event);
}



void MainUI::slot_login_success()
{
    //跨线程 信号槽传递结构体还需要注册
   //QVariant -> struct st_userInfo

   /*
    修改头像: 服务器存储图像,客户端显示头像就从服务器下载
            修改头像,将头像上传给服务器,并以DD号命名(使图片唯一),后期再修改头像就覆盖之前的头像
            两个默认头像 man.png woman.png 是初创账号头像,保留
    */
   QString hname = QString("%1.png").arg(GlobalObject::getGlobalObject()->getUserInfo().sdata.dd_num);
   QString head_url = QString("%1/%2").arg(PATH_IMG).arg(hname);
   // 设置头像
   ui->lab_head->setPixmap(PixmapToRoundOpenCV(downLoadFromUrl(head_url)));
   ui->lab_nick->setText(GlobalObject::getGlobalObject()->getUserInfo().sdata.nick);  //昵称
   if(GlobalObject::getGlobalObject()->getUserInfo().sdata.status == 1){
        ui->lab_status->setText("[在线]");
   }

   // 加载好友列表和群组列表
   loadFriendsGroups();

   //初始化添加好友窗口
   addwindow = new AddWindow;
   // 初始化通知窗口
   initNoticeWindow();
   // 初始化创建群聊窗口
   creategroupwindow = new CreateGroupWindow;
   // 初始化编辑个人资料窗口
   modifyinfowindow = new ModifyInfoWindow(GlobalObject::getGlobalObject()->getUserInfo().sdata);
   // 初始化修改密码窗口
   modifypwdwindow = new ModifyPwdWindow;
   // 初始化龙通讯窗口
   aboutDIMwindow = new AboutDIMWindow;
   // 初始化朋友圈
   pyqwindow = new PYQWindow;
   // 初始化AI聊天
   aichatwindow = new AIChatWindow(GlobalObject::getGlobalObject()->getUserInfo().sdata);

   struct st_personData udata = GlobalObject::getGlobalObject()->getUserInfo().sdata;
   // 初始化好友聊天窗口
   for(int i = 0;i<GlobalObject::getGlobalObject()->getUserInfo().friend_list.size();i++){
       struct st_friendData fdata = GlobalObject::getGlobalObject()->getUserInfo().friend_list[i];
       PrivateChatWindow* pchatwindow = new PrivateChatWindow(udata,fdata);
       map_chatwindow.insert(fdata.dd_num,pchatwindow);
   }

   // 初始化好友个人资料窗口
   for(int i = 0;i<GlobalObject::getGlobalObject()->getUserInfo().friend_list.size();i++){
       struct st_friendData fdata = GlobalObject::getGlobalObject()->getUserInfo().friend_list[i];
       FriendInfoWindow* infowindow = new FriendInfoWindow(fdata);
       map_finfowindow.insert(fdata.dd_num,infowindow);
       connect(infowindow,&FriendInfoWindow::sig_infoWindowShow,this,[=](int fid){
           map_chatwindow[fid]->show();
       });
   }

   // 初始化群聊天窗口
   for(int i = 0;i<GlobalObject::getGlobalObject()->getUserInfo().group_list.size();i++){
       struct st_gData gdata = GlobalObject::getGlobalObject()->getUserInfo().group_list[i];
       GroupChatWindow* groupchatwindow = new GroupChatWindow(udata,gdata);
       map_groupchatwindow.insert(gdata.gid,groupchatwindow);
   }

   // 初始化群资料窗口
   for(int i = 0;i<GlobalObject::getGlobalObject()->getUserInfo().group_list.size();i++){
       struct st_gData gdata = GlobalObject::getGlobalObject()->getUserInfo().group_list[i];
       GroupInfoWindow* groupwindow = new GroupInfoWindow(gdata);
       map_ginfowindow.insert(gdata.gid,groupwindow);
       connect(groupwindow,&GroupInfoWindow::sig_ginfoWindowShow,this,[=](int gid){
           map_groupchatwindow[gid]->Show();
       });
   }



}

void MainUI::on_treeWidget_itemPressed(QTreeWidgetItem *item, int column)
{
    Q_UNUSED(column);
    if(qApp->mouseButtons() == Qt::RightButton)   //判断是否为右键
        {
            //根节点不响应,判断有没有父节点来确定其是否是根节点
            if(item->parent()!=nullptr && item->parent()->text(0)=="我的好友"){
                menu->clear();
                menu->addAction(action_userinfo);
                menu->addAction(private_chat);
                menu->addAction(delete_friend);
                //获取点击的item对应的UID
                GlobalObject::getGlobalObject()->setCurrentSelectUid(item->data(0,Qt::UserRole).toInt());
                //qDebug()<<item->data(0,Qt::UserRole).toInt();
                menu->exec(QCursor::pos());   //菜单弹出位置为鼠标点击位置
            }else if(item->parent()!=nullptr && item->parent()->text(0)=="群聊"){
                menu->clear();
                menu->addAction(action_groupinfo);
                menu->addAction(group_chat);
                menu->addAction(quit_group);
                //获取点击的item对应的群ID
                GlobalObject::getGlobalObject()->setCurrentSelectGid(item->data(0,Qt::UserRole).toInt());
                //qDebug()<<item->data(0,Qt::UserRole).toInt();
                menu->exec(QCursor::pos());   //菜单弹出位置为鼠标点击位置
            }
        }
}


void MainUI::on_btn_addFriend_clicked()
{
    //添加好友/群窗口
    addwindow->show();
}


void MainUI::on_btn_notice_clicked()
{
    //通知窗口
    noticewindow->show();
}

void MainUI::updateNoticeIcon(int flag)
{
    switch(flag){
    case 0: ui->btn_notice->setStyleSheet("QPushButton{border-image: url(:/prefix2/software/wumsg.png);}");
        break;
    case 1:ui->btn_notice->setStyleSheet("QPushButton{border-image: url(:/prefix2/software/youmsg.png);}");
        break;
    }
}

void MainUI::updateFriendStatus(int uid, int status)
{
    //更新好友链表中的状态
    GlobalObject::getGlobalObject()->updateFriendStatus(uid,status);

    //更新TreeWidget UI界面
    //遍历QTreeWidgetItem
   QTreeWidgetItemIterator it(root_friend);   //遍历好友节点
   while(*it){
       if((*it)->data(0,Qt::UserRole).toInt() == uid){
           ui->treeWidget->removeItemWidget((*it),0);       //删除Item的Widget后重新设置
           ui->treeWidget->setItemWidget((*it),0,new MyTreeWidgetItem(st_treeItem(GlobalObject::getGlobalObject()->getFriendInfo(uid),TI_FRIEND)));
           return;
       }
       it++;
   }

}


void MainUI::on_btn_creategroup_clicked()
{
    creategroupwindow->show();
}


void MainUI::on_btn_close_clicked()
{
    this->close();
}


void MainUI::on_btn_min_clicked()
{
    // 最小化
    this->showMinimized();
}

void MainUI::on_btn_ui_clicked()
{
    // 6代表当前theme目录下有6种主题
    int num = ++sunsetNum%6;
    QString style = QString("QWidget#widget_header{border-image: url(:/theme/software/sunset%1.jpg);}").arg(num);
    ui->widget_header->setStyleSheet(style);
}


void MainUI::on_btn_set_clicked()
{
    // 按钮全局坐标,相对应屏幕左上角的坐标
    QPoint btn_pos = ui->btn_set->mapToGlobal(QPoint(0, 0));
    // x不变, y = y -  菜单的高
    set_menu->exec(QPoint(btn_pos.x(), btn_pos.y() - set_menu->sizeHint().height()));
}


void MainUI::on_btn_pyq_clicked()
{
    pyqwindow->Show();
}

QMap<int, GroupChatWindow *> MainUI::getMap_groupchatwindow() const
{
    return map_groupchatwindow;
}

PYQWindow *MainUI::getPyqwindow() const
{
    return pyqwindow;
}


void MainUI::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    int id = item->data(0,Qt::UserRole).toInt();

    if(item->parent()->text(0) == "我的好友")
    {
        // 打开窗口表示未读消息已全部读完
        emit map_treeitem[id]->sig_noread_flag(1);
        map_chatwindow[id]->show();
    }
    else if(item->parent()->text(0) == "群聊")
    {
        // 打开窗口表示未读消息已全部读完
        emit map_treeitem[id]->sig_noread_flag(3);
        map_groupchatwindow[id]->Show();
    }
}

CreateGroupWindow *MainUI::getCreategroupwindow() const
{
    return creategroupwindow;
}

